<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/6/22
 * Time: 13:41
 */

namespace common\models\Service;


use common\models\Cache;
use common\models\CommonFunction;
use common\models\DAO\DayAccrual;
use common\models\DAO\PocketFund;
use common\models\DAO\PocketFundList;
use common\models\DAO\User;
use common\models\DAO\UserInvest;
use common\models\DAO\UserInvestList;
use common\models\DAO\UserWalletLog;
use common\models\Http;
use common\msg\UserMsg;

class FundService {
	
    /*
     * 检查用户是否投资新手标
     */
    public static function check($userID){
        $fund = PocketFundList::findOne(array('userID'=>$userID));
        if($fund)
            return true;
        return false;
    }

    /*
     * 获取新手标信息
     */
    public static function get(){
        //Cache::clear('pocket_fund');die;
        $pocket_fund = Cache::get('pocket_fund');
        if(!$pocket_fund){
            $pocket_fund = PocketFund::findOne(1)->attributes;
            Cache::set('pocket_fund', $pocket_fund);
        }
        return $pocket_fund;
    }

    /*
     * 首页新手标信息
     */
    public static function getInfo(){
        $info = self::get();
        if(empty($info['person'])){
            $info['person'] = PocketFundList::find()->count();
            Cache::set('pocket_fund', $info);
        }
        return $info;

    }
    /*
     * 页面初始化
     */
    public static function init($userID){
        $info = self::get();
        if(!$info){
            $result['status'] = 0;
            return $result;
        }
        $fund = intval($info['money']);
        $system_day = \Yii::$app->params['system_day'];
        $money = intval(($fund + 1) * intval($info['rate']) * intval($info['day']) / $system_day / 10000);
        $income = CommonFunction::formatMoney($money);
        $result['income'] = $income;
        $result['all'] = $money/100 + 0.01;
        $result['info'] = $info;
        $result['remainder'] = CommonFunction::formatMoney(Wallet::remainder($userID));
        $result['or_remainder'] = intval(Wallet::remainder($userID)) / 100;
        $result['count'] = PocketFundList::find()->count();
        $result['list'] = self::getList();
        return $result;
    }

    /*
     * 新手标信息
     */
    public static function info(){
        $info = self::get();
        if(!$info){
            $result['status'] = 0;
            return $result;
        }
        $fund = intval($info['money']);
        $system_day = \Yii::$app->params['system_day'];
        $money = intval(($fund + 1) * intval($info['rate']) * intval($info['day']) / $system_day / 10000);
        $income = CommonFunction::formatMoney($money);
        $result['income'] = $income;
        $result['all'] = $money/100 + 0.01;
        $result['info'] = $info;
        $result['count'] = PocketFundList::find()->count();
        $result['list'] = self::getList();
        return $result;
    }
    /*
     *获取新手标投资列表
     */
    public static function getList($page = 1, $limit = 10){
        $start = ($page - 1) * $limit;
        $list = PocketFundList::find()->with('user')->limit($limit)->offset($start)->orderBy('id asc')->all();
        $result = array();
        if($list){
            foreach($list as $v){
                $_list = [];
                $phone = CommonFunction::decrypt(($v['user']['phone']));
                $_list['phone'] = substr($phone,  0, 3) . '****' . substr($phone,  -4, 4);
                $_list['time'] = date('Y-m-d H:i',$v['createTime']);
                $result[] = $_list;
            }
        }
        return $result;
    }
    /*
     * 新手标投资
     */
    public static function invest($_userInfo){
		$userID = $_userInfo['userID'];
        //$status = self::check($userID);
        $result['status'] = 0;
        $result['msg'] = UserMsg::$time_out;
        /* if($status){
            $result['msg'] = UserMsg::$alread_fund_invest;
            return $result;
        } */
        $is_charge = DayAccrual::find()->where(['userID'=>$userID])->andWhere('chargeID!=0')->count('id');
        if($is_charge == 0 ){
            $result['msg'] = '亲，新手标需要您充值后即可投资哦。';
            return $result;
        }
        $remainder = intval(Wallet::remainder($userID)) / 100;
        if($remainder < 0.01){
            $result['msg'] = UserMsg::$no_money;
            return $result;
        }
        $fund_info = self::get();
        if(!$fund_info){
            $result['msg'] = UserMsg::$action_end;
            return $result;
        }
        $rate = intval($fund_info['rate']);
        $day = intval($fund_info['day']);
        $fund = intval($fund_info['money']);
        $system_day = \Yii::$app->params['system_day'];
        $money = intval(($fund + 1) * $rate * $day / $system_day / 10000);
        $title = $fund_info['title'];
        $start_date =  date("Ymd",strtotime("+1 day"));
        $over_day = $day + 1;
        $end_date =  date("Ymd",strtotime("+$over_day day"));
        $now = time();
        $transaction = \Yii::$app->db->beginTransaction();
        $userModel = User::findOne($userID);
        $userModel->isNew = 0;
        $user_result = $userModel->save();
        if(!$user_result){
            $transaction->rollBack();
            return $result;
        }
        $fundList = new PocketFundList();
        $fundList->userID = $userID;
        $fundList->createTime = $now;
        $fundList->rate = $rate;
        $fundList->money = $fund + 1;
        $fundList->day = $day;
        $fundList->hongbao = $fund;
        $fund_result = $fundList->save();
        if(!$fund_result){
            $transaction->rollBack();
            return $result;
        }
        $userInvest = new UserInvest();
        $userInvest->userID = $userID;
        $userInvest->FundID = $fund_info['id'];
        $userInvest->title = $title;
        $userInvest->endTime = $end_date;
        $userInvest->startTime = $start_date;
        $userInvest->money = 1;
        $userInvest->accrual = $money;
        $userInvest->typeID = 1;
        $userInvest->rate = $rate;
        $userInvest->createTime = $now;
        $invest_result = $userInvest->save();
        if(!$invest_result){
            $transaction->rollBack();
            return $result;
        }
        $invest_result = $userInvest->id;
        $accrual = DayAccrual::find()->where(array('userID'=>$userID))->andFilterWhere(['>', 'money', 0])->orderBy('date asc')->all();
        $init_money = 1;
        $investList = new UserInvestList();

        //钱包明细
        $user_wallet = new UserWalletLog();
        $user_wallet->type = 2;
        $user_wallet->investID = $fund_info['id'];
        $user_wallet->money = $init_money;
        $user_wallet->createTime = $now;
        $user_wallet->userID = $userID;
        $user_wallet->road = 2;
        $user_wallet->userInvestID = $invest_result;
        $user_wallet_result  = $user_wallet->save();
        if(!$user_wallet_result){
            $transaction->rollBack();
            return $result;
        }
        foreach($accrual as $v){
            $money = intval($v['money']);
            $id = $v['id'];
            if($money <= 0)
                continue;
            if($money < $init_money){
                $accrual_one = DayAccrual::findOne($id);
                $accrual_one->money = 0;
                $accrual_one->updateTime = $now;
                $one_result = $accrual_one->save();
                if(!$one_result){
                    $transaction->rollBack();
                    return $result;
                }
                $investList->userID = $userID;
                $investList->userInvestID = $invest_result;
                $investList->FundID = $fund_info['id'];
                $investList->money = $money;
                $investList->createTime = $now;
                $investList->accrualID = $id;
                $list_result = $investList->save();
                if(!$list_result){
                    $transaction->rollBack();
                    return $result;
                }
                $init_money = $init_money - $money;
            }else{
                $accrual_one = DayAccrual::findOne($id);
                $accrual_one->money = $money - $init_money;
                $accrual_one->updateTime = $now;
                $one_result = $accrual_one->save();
                if(!$one_result){
                    $transaction->rollBack();
                    return $result;
                }
                $investList->userID = $userID;
                $investList->investID = $fund_info['id'];
                $investList->userInvestID = $invest_result;
                $investList->typeID = 1;
                $investList->money = $init_money;
                $investList->createTime = $now;
                $investList->accrualID = $id;
                $list_result = $investList->save();
                if(!$list_result){
                    $transaction->rollBack();
                    return $result;
                }
                break;
            }
        }
        $userInfo = Http::session('user');
        $userInfo['isNew'] = 0;
        Http::session('user', $userInfo);
        $transaction->commit();
        $info = self::get();
        if(!empty($info['person'])){
            $info['person'] = intval($info['person']) + 1;
            Cache::set('pocket_fund', $info);
        }
        if(!empty($_userInfo['recID'])){
            $integral_data = $_userInfo;
            $integral_data['type'] = 5;
            $integral_data['integral'] = 150;
            $integral_data['des'] = '好友'.CommonFunction::dealTel($_userInfo['tel']).'完成新手任务。';
            IntegralService::addIntegral($integral_data);
        }
        return array('status'=>1, 'url'=> \Yii::$app->urlManager->createUrl(['invest/index', 'id' => $invest_result]),'id'=>$invest_result);
    }
}